const { ipcRenderer } = window.require("electron");
import { useEffect, useState } from "react";
import { history } from "umi";

export default () => {
  const [deviceList, setDeviceList] = useState<any[]>([]);
  const [linkType, setLinkType] = useState("hdc");
  const [deviceInfo, setDeviceInfo] = useState<any>(null);

  useEffect(() => {
    ipcRenderer.on("freshDeviceList", () => {
      getDeviceList();
    });
  }, []);

  useEffect(() => {
    deviceList.length
      ? window.postMessage("stopWatch")
      : window.postMessage("startWatch");
  }, [deviceList]);

  useEffect(() => {
    if (history.location.pathname === "/auth") {
      setDeviceList([]);
    }
  }, [history]);

  const getDeviceList = async () => {
    try {
      const list = await ipcRenderer.invoke("getDeviceListByHdc");
      if (list?.length) {
        setDeviceList(list);
        setLinkType("hdc");
      } else {
        setDeviceList(await ipcRenderer.invoke("getDeviceListByAdb"));
        setLinkType("adb");
      }
    } catch (err) {
      console.log(err);
    }
  };

  const getDeviceInfo = async (SN: string) => {
    let device =
      deviceList.find((item) => item.SN === SN || item.serialno === SN) ||
      deviceList[0] ||
      {};
    if (!device.SN) {
      return device;
    }
    try {
      if (linkType === "hdc") {
        const info = await ipcRenderer.invoke("getDeviceInfoByHdc", device.SN);
        device = {
          ...device,
          ...info,
        };
      } else {
        const info = await ipcRenderer.invoke("getDeviceInfoByAdb", device.SN);
        device = {
          ...device,
          ...info,
        };
      }
    } catch (err) {
      console.log(err);
    }
    return device;
  };

  return {
    deviceList,
    setDeviceList,
    getDeviceList,
    getDeviceInfo,
    deviceInfo,
    setDeviceInfo,
    linkType,
  };
};
